<template>
  <div class="login-container">
    <div class="login-box">
      <h2>系统登录</h2>
      <el-form :model="loginForm" label-width="100px">
        <el-form-item label="Client ID">
          <el-input v-model="loginForm.clientId" placeholder="请输入Client ID" />
        </el-form-item>
        <el-form-item label="Client Secret">
          <el-input v-model="loginForm.clientSecret" type="password" placeholder="请输入Client Secret" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" :loading="loading">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import {inject, ref} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getToken } from '../api/auth'
const $http = inject("$axios")
const router = useRouter()
const loading = ref(false)
const loginForm = ref({
  clientId: '',
  clientSecret: ''
})
const login  = async()=>{
  const  res =await $http.post('/user/login',{
    username:loginForm.value.clientId,
    password:loginForm.value.clientSecret,
  })

  if(res?.data == true){
    await handleLogin()
  }else {
    ElMessage.error( '登录失败')
  }
}
const handleLogin = async () => {
  try {
    loading.value = true
    const res = await getToken(loginForm.value.clientId, loginForm.value.clientSecret)
    if (res.data.access_token) {
      // 保存token
      debugger
      localStorage.setItem('token', res.data.access_token)
      // 保存过期时间
      const expiresIn = res.data.expires_in
      localStorage.setItem('tokenExpires', Date.now() + expiresIn * 1000)
      
      ElMessage.success('登录成功')
      router.push('/greenhouse')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.error_description || '登录失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #001529;
}

.login-box {
  width: 400px;
  padding: 30px;
  background: #071526;
  border: 1px solid #33f2dc;
  border-radius: 8px;
}

h2 {
  color: #33f2dc;
  text-align: center;
  margin-bottom: 30px;
}

:deep(.el-input__inner) {
  background: #0a2744;
  border-color: #33f2dc;
  color: #fff;
}

:deep(.el-form-item__label) {
  color: #33f2dc;
}
</style>